<?php
require_once dirname(__FILE__).'/../lib/BasesfGuardAuthActions.class.php';
/**
 * sfGuardAuth plugin overriden actions
 *
 * @package    symfony
 * @subpackage plugin
 */
class sfGuardAuthActions extends BasesfGuardAuthActions
{


  /**
   * Registers a new member
   *
   * @param     sfWebRequest $request
   * @sf_param  array  user  Member form informations
   */

     public function executeExit(sfWebRequest $request)
  {

      $user = $this->getUser()->signout();
      $remember_cookie = sfConfig::get('app_sf_guard_plugin_remember_cookie_name', 'sfRemember');
      sfContext::getInstance()->getResponse()->setCookie($remember_cookie, '');
      sfContext::getInstance()->getResponse()->setCookie('sfRemember', '');
   
      $this->redirect('@homepage');
  }
	
	 public function executeCheckregister(sfWebRequest $request)
  {
  	$this->setDecorator();
  }
	
  public function executeRegister(sfWebRequest $request)
  {
  	
  	$str_form=sfConfig::get('app_name').'RegisterForm';
  	
  	$this->setDecorator();
  	//echo DOMAIN.'-'.$_SERVER['SERVER_NAME']; 
    if ($this->getUser()->isAuthenticated())
    {
      $this->redirect('@welcome');
    }
    
   
    $this->form = new $str_form();

    $params = $request->getParameter('user', array());

    if (true === sfConfig::get('app_recaptcha_enabled', true))
    {
      $captcha = array (
        'recaptcha_challenge_field' => $request->getParameter('recaptcha_challenge_field'),
        'recaptcha_response_field'  => $request->getParameter('recaptcha_response_field'),
      );

      $params = array_merge($params, array('captcha' => $captcha));
    }
   
    //if (!$request->isMethod('post') or !$this->form->bindAndSave($params))
    if ($request->isMethod('post'))
    {
      
    	$this->form->bind($request->getParameter('user'));
    if ($this->form->isValid())
      {
      	sfLoader::loadHelpers ( 'I18N' );
      	////Создаем профайл
      	//$profile=new Profile();
      	$sf_guard_user = new sfGuardUser();
      	if(sfConfig::get('app_use_id_login')==true)
      	{
      		$sf_guard_user->setNickname($this->form->getValue('username'));
      	}
      	else 
      	{
      		$sf_guard_user->setUsername($this->form->getValue('username'));
      	}
      	
      	$sf_guard_user->setPassword($request->getParameter('user[password]'));
      	$sf_guard_user->setEmail($request->getParameter('user[email]'));
      	$sf_guard_user->setNickname($request->getParameter('user[username]'));
        $sf_guard_user->setFirstName($request->getParameter('user[username]'));
      	$sf_guard_user->setGender('m');
      	$sf_guard_user->setCountry($request->getParameter('user[country]'));
      	$sf_guard_user->setAccount(0);
      	$sf_guard_user->setPartnerId(1);
      	$sf_guard_user->setIsActive(false);
      	
      	
      	
        $sf_guard_user->save();
        
        ////Генерируем ID
        if(sfConfig::get('app_use_id_login')==true)
        {
        	$simb = array('a','b','c','d','f','g','l','k');
        	$r1 = rand(0,7);
        	$r2 = rand(0,7);
        	$r3 = rand(0,7);
        	$login = $simb[$r1].$simb[$r2].$simb[$r3].$sf_guard_user->getId();
        	$sf_guard_user->setUsername($login);
        	$sf_guard_user->save();
        }
        ////
      	
    	//$profile->setUserId($sf_guard_user->getId());
    	//$profile->setEmail($this->form->getValue('email'));
    	//$profile->save();
    	
    	
    //// Шлем уведомление	
      
      $not=MailnoticePeer::retrieveByPK(1);    
      $title = $not->getTitle();
      
      

        $body=$not->parse_body(array(
        	  '%URL1%'=>"http://".$_SERVER['SERVER_NAME'],
	          '%login%'=>$login,
	          '%pass%'=>$this->form->getValue('password'),
	          '%link%'=>"<a href='http://".$_SERVER['SERVER_NAME'].'/index.php/Activate/user/code/'.$sf_guard_user->getSalt()."'>".__('ссылку')."</a>",
	          '%link_char%'=>'http://'.$_SERVER['SERVER_NAME'].'/index.php/Activate/user/code/'.$sf_guard_user->getSalt()    
	      ),$this->getUser()->getCulture());
      
      //$body="Вы зарегистрировались на сайте <a href='http://localhost:82/pressa/web/Activate/user/code/".$this->sf_guard_user->getSalt()."'>activation link</a>";
      myTools::sendMail($this->form->getValue('email'),$title,$body);	
      /////

      
       $this->getUser ()->setFlash ( 'message', 'Вы успешно зарегистрированы и вам на e-mail выслано писмо с сыллкой для активации' );
      
      if(sfConfig::get('app_activation_after_reg')==true)
      {
      	$this->redirect('@done_registration');
      }
      else 
      {
      	
    	$this->getUser()->signin($sf_guard_user);
    	$this->redirect('@welcome');
      }
    	
      } 
    	
    }
    }

   public function executeSignin(sfWebRequest $request)
  {
  	$this->setDecorator();
    $user = $this->getUser();
    if ($user->isAuthenticated())
    {
      return $this->redirect('@welcome');
    }

    $this->form = new SigninForm();

    if ($request->isMethod('post'))
    {
      $this->form->bind($request->getParameter('signin'));

      if ($this->form->isValid())
      {
        $values = $this->form->getValues();
        $this->getUser()->signin($values['user'], 'on' === $values['remember']);
        $signinUrl = sfConfig::get('app_sf_guard_plugin_success_signin_url', $request->getReferer());
        return $this->redirect('profile/mypage');
        
      }
    }
    else
    {
      if ($request->isXmlHttpRequest())
      {
        $this->getResponse()->setHeaderOnly(true);
        $this->getResponse()->setStatusCode(401);

        return sfView::NONE;
      }

      $user->setReferer($request->getReferer());

      $module = sfConfig::get('sf_login_module');
      if ($this->getModuleName() != $module)
      {
        return $this->redirect($module.'/'.sfConfig::get('sf_login_action'));
      }
        return $this->redirect('errorpage/secure');
    }
  }
    
    



  
  public function executeSuperlogin()
  {
    
  	    $c= new Criteria();
  		$c->add(sfGuardUserPeer::ID, $this->getRequestParameter('id'));
        $user=sfGuardUserPeer::doSelectOne($c);
        //$user->setIsActive(1);
        //$user->save();
        
  	    
          $this->getContext()->getUser()->signIn($user);
         $user = $this->getUser();

         $user->addCredential('admin');
  	
  	$this->redirect('@my_profile'); 	
  }
  
  
	public function setDecorator()
	{
		
		$module = $this->getRequest()->getParameter('module');
		$action = $this->getRequest()->getParameter('action');
		
		$path_layout = sfConfig::get('sf_app_template_dir').'/layouts/'.sfConfig::get('app_name').'/'.$module.'.php';
		$path_template = sfConfig::get('sf_app_module_dir').'/'.$module.'/templates/'.sfConfig::get('app_name').'/'.$action.'Success.php';
		if(file_exists($path_layout))
		{ $l = 'layouts/'.sfConfig::get('app_name').'/'.$module; }
		else
		{ $l = sfConfig::get('app_name').'_layout'; }
		if(file_exists($path_template))
		{ $t = sfConfig::get('app_name').'/'.$action; }
		else
		{ $t = $action; }
			
	/*
     * Установка layout
     */	
			$this->setLayout ( $l );
		
     /*
     *  Устанавливаем шаблон
     */
		
			$this->setTemplate ( $t );
	}

}
